/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package tanqueDeAgua;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

/**
 *
 * @author pabloramix
 */
public class Pipe extends Thread implements ChangeListener {

    public static enum Direction {
        IN,
        OUT
    }
    
    public static long PRIORITY = 20;
    
    private double caudal;
    private boolean running;
    private final Tank myTank;
    private final Direction myDirection; 
    private final String name;
    
    public Pipe (Tank tank, Direction direction, double caudal, String name) {
        this.myTank = tank;
        this.myDirection = direction;
        this.caudal = caudal;
        this.running = false;
        this.name = name;
    }
    
    /**
     * @return the caudal
     */
    public double getCaudal() {
        return caudal;
    }

    /**
     * @param caudal the caudal to set
     */
    public void setCaudal(double caudal) {
        this.caudal = caudal;
    }

    /**
     * @return the myDirection
     */
    public Direction getMyDirection() {
        return myDirection;
    }
    
    public void terminate() {
        this.running = false;
    }
    
    public String getStatusString() {
        return name + " | " + (this.isAlive() ? "Alive" : "Not Alive" ) + " | " + this.getState();
    }
    
    @Override
    public void run() {
        running=true;
        while (running) {
            try {
                myTank.fill((getMyDirection() == Direction.IN) ? (getCaudal() * PRIORITY / 1000 ) : (-1) * (getCaudal() * PRIORITY / 1000 ));
                System.out.println("Pipe " + (getMyDirection() == Direction.IN ? "IN" : "OUT") + " -- Tank Level: " + myTank.getLevel());
                Pipe.sleep(PRIORITY);
            } catch (InterruptedException ex) {
                Logger.getLogger(Pipe.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    @Override
    public void stateChanged(ChangeEvent e) {
        JSlider s = (JSlider) e.getSource();
        this.setCaudal(s.getValue()/10.0);
    }
}
